package com.chenjunlin.shortlink.admin.common.userContext;

import com.alibaba.fastjson2.JSON;
import com.chenjunlin.shortlink.admin.common.constant.RedisConstant;
import com.chenjunlin.shortlink.admin.common.convention.exception.ClientException;
import com.chenjunlin.shortlink.admin.common.enums.UserErrorCodeEnun;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jodd.util.StringUtil;
import lombok.RequiredArgsConstructor;
import org.apache.curator.shaded.com.google.common.collect.Lists;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.IOException;
import java.util.List;
import java.util.Objects;


/**
 * 用户信息传输过滤器
 *
 */
@RequiredArgsConstructor
public class UserTransmitFilter implements Filter {

    private final RedisTemplate redisTemplate;
//    排除用户名有效查询、检查是否登录、以及用户登录时的token拦截
    private static final List<String> IGNORE_URI = Lists.newArrayList(
            "/api/short-link/admin/v1/user/has-username",
                    "/api/short-link/admin/v1/user/check-login",
                    "/api/short-link/admin/v1/user/login");

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String requestURI = httpServletRequest.getRequestURI();
        if(!IGNORE_URI.contains(requestURI)){
            String method = httpServletRequest.getMethod();
            //排除用户注册时的token拦截
            if(!(Objects.equals(requestURI,"/api/short-link/admin/v1/user")&& Objects.equals(method,"POST"))){
                String userName = httpServletRequest.getHeader("username");
                String token = httpServletRequest.getHeader("token");
                if(StringUtil.isAllBlank(userName,token)){
                    throw new ClientException(UserErrorCodeEnun.USER_TOKEN_FAIL);
                }

                Object userInfoJsonStr = redisTemplate.opsForHash().get(RedisConstant.LOGIN_USER_KEY + userName, token);
                    if(userInfoJsonStr == null){
                        throw new ClientException(UserErrorCodeEnun.USER_TOKEN_FAIL);
                    }

                    UserInfoDTO userInfoDTO = JSON.parseObject(userInfoJsonStr.toString(), UserInfoDTO.class);
                    UserContext.setUser(userInfoDTO);
            }
        }
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            UserContext.removeUser();
        }
    }
}